package com.yonyou.cyxdms.basedata.service.util;

import com.xiaoleilu.hutool.lang.Assert;
import com.yonyou.cyxdms.basedata.client.domains.vo.CodeVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonCodeService;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 校验工具类
 *
 * @author lyz
 * @date 2020/11/25
 */
@Component
public class CheckUtil {

    @Autowired
    private BaseCommonCodeService baseCommonCodeService;

    /**
     * 判断codeId是否数据type类型下字典之一
     * 一般用于导入的字典校验
     *
     * @param type   字典类型
     * @param codeId 字典值
     * @author lyz
     * @date 2020/11/24
     */
    public boolean dictIsContain(String type, Integer codeId) {
        List<CodeVO> list = baseCommonCodeService.getCodeListByType(type);
        return ListUtils.emptyIfNull(list).stream().anyMatch(codeVO -> codeVO.getCodeId().equals(codeId));
    }

    /**
     * 导入文件公共校验
     *
     * @author lyz
     * @date 2021/1/4
     */
    public void importFileCheck(MultipartFile file) {
        Assert.notNull(file, "导入模版必传！");
        Assert.notEmpty(file.getOriginalFilename(), "模版必须有文件名！");
        String filename = file.getOriginalFilename();
        String type = filename.substring(filename.lastIndexOf("."));
        Assert.isTrue(StringUtils.equals(type, ".xlsx"), "导入表格必须是xlsx文件！");
    }

    /**
     * 导入文件公共校验
     *
     * @author lx
     * @date 2021/1/4
     */
    public void importCheck(MultipartFile file) {
        Assert.notNull(file, "导入模版必传！");
        Assert.notEmpty(file.getOriginalFilename(), "模版必须有文件名！");
        String filename = file.getOriginalFilename();
        String type = filename.substring(filename.lastIndexOf("."));
        Assert.isTrue(StringUtils.equals(type, ".xls"), "导入表格必须是xls文件！");
    }

}
